/*先引进去:
mui.min.css
cropper.css
mui.min.js
jquery.min.js
cropper.js
qiniuupload.js
*/
/*	
 * 
 * qiniuupload({
		uploadListId: "uploadList",		//待上传图片列表
		startUploadId: "startUpload",	//开始上传按钮
		uploadMax:6,					//一次最大上传数量
		hideLoaded:false,				//清除已上传
		uptokenUrl: 'http://10.8.45.1:8080/qiniuTest/getToken?bucket=test1',	//获取服务器验证七牛uptoken的服务器地址
		picUrl: "http://ongwb2t5i.bkt.clouddn.com"					//七牛账号的图片地址
	});
*/
var xhrNumber = 0; //一次上传完成时=0，有未完成<0
function qiniuupload(obj) {
	var headId = "";
	var addId = "";
	//	var xhrNumber = 0;
	editAndpicAndcss(); //添加元素,包括样式，mui的选择actionsheet,裁剪的结构
	getUptoken(); //获取服务器uptoken
	cutImg().addevent();
	$("a.mui-icon-plus").on("tap", function() {
		addId = this.id;
	});
	mui('#picture').on('tap', '.mui-popover-action li>a', function() { //呼出的actionsheet菜单
		var a = this;
		//根据点击按钮，反推当前是哪个actionsheet
		if(a.id == "getImage") {
			getImage();
		} else if(a.id == "galleryImgs") {
			galleryImgs();
		};
		mui('#picture').popover('toggle');
	});
	$("#" + obj.startUploadId).click(function() { //点击开始上传事件
		if($(this).hasClass("mui-disabled")) return;
		xhrNumber = 0;
		$("p.btnlist").addClass("mui-hidden");
		var $uploadimgArr = $("a.mui-icon-plus").length > 0 ? $("a.mui-icon-plus").parent().find(".pic").not($(".uploadsuccess")) : $(".pic").not($(".uploadsuccess"));
		if($uploadimgArr.length == 0) return;
		$uploadimgArr.addClass("uploading mui-icon mui-spinner-custom mui-spin");
		$("#" + obj.startUploadId).addClass("mui-disabled");
		$uploadimgArr.each(function(index, divItem) {
			//			var $imgI = $(divItem).addClass("mui-disabled").find("img");
			var $imgI = $(divItem).find("img");
			getBase64($imgI);
		});
		getUptoken(true);
	});
	$("#" + obj.uploadListId)[0].addEventListener("tap", function(ev) { //编辑和删除按钮的事件委托
		var ev = ev || window.event;
		var target = ev.target || ev.srcElement;
		//		alert(target.nodeName)
		if(target.nodeName == 'IMG') { //是点击的图片，隐藏或者显示按钮
			var $p = $(target.previousElementSibling);
			if($p.hasClass("mui-hidden")) {
				$p.removeClass("mui-hidden");
			} else {
				$p.addClass("mui-hidden");;
			};
			if($(target).parent().attr("href")) {
				headId = $(target).parent().attr("id");
			}
		} else if($(target).hasClass("pic")) {
			if($(target).attr("href")) {
				headId = $(target).attr("id");
			} else {
				var $p = $(target).find("p");
				if($p.hasClass("mui-hidden")) {
					$p.removeClass("mui-hidden");
				} else {
					$p.addClass("mui-hidden");;
				};
			}
		} else if(target.nodeName == "BUTTON") { //点击的是按钮，根据按钮选择功能
			var $btn = $(target);
			if($btn.hasClass("mui-icon-trash")) {
				var $pic = $btn.parent().parent();
				//var $uploadimgArr = $("#" + obj.uploadListId + " .pic").not($(".mui-disabled"));
				var $uploadimgArr = $pic.parent().find(".pic");
				//				console.log($uploadimgArr.length)
				if($uploadimgArr.length == 0) {
					$("#" + obj.startUploadId).addClass("mui-disabled");
				};
				if($uploadimgArr.length <= obj.uploadMax) {
					$pic.parent().find(".mui-icon-plus").show();
				};
				$pic.remove();
			} else {
				var src = $btn.parent().siblings().attr("src");
				$btn.parent().siblings().addClass("cuting");
				cutImg().showEdit(src);
			};
			$btn.parent().addClass("mui-hidden");
		};
	});
	$("#capture").on("change", function() {
		//		console.log(this.files)
		if(headId == "" && $("#" + addId).parent().find(".pic").length + $(this.files).length > obj.uploadMax) {
			mui.toast("最多能添加" + obj.uploadMax + "张");
		} else {
			$(this.files).each(function(n, item) {
				var blob = URL.createObjectURL(item);
				getImagefile(blob);
			})
		};

	});

	function editAndpicAndcss() {
		var strEdit = ""; //裁剪的结构和actionsheet
		var strAction = "";
		var strCss = ""; //样式
		var strAdd = ""; //添加按钮

		strEdit += "<div id=\"showEdit\">\n";
		strEdit += "	<div id=\"report\">\n";
		strEdit += "		<img id=\"readyimg\">\n";
		strEdit += "	<\/div>\n";
		strEdit += "	<div class=\"flex-container\">\n";
		strEdit += "		<a id='closepop'><span class=\"mui-icon mui-icon-closeempty\"><\/span>关闭<\/a>\n";
		strEdit += "		<a id='rotateimgleft'><span class=\"mui-icon mui-icon-undo\"><\/span>左旋转<\/a>\n";
		strEdit += "		<a id='rotateimg'><span class=\"mui-icon mui-icon-redo\"><\/span>右旋转<\/a>\n";
		strEdit += "		<a id='resetpop'><span class=\"mui-icon mui-icon mui-icon-reload\"><\/span>重置<\/a>\n";
		strEdit += "		<a id='confirm'><span class=\"mui-icon mui-icon-checkmarkempty\"><\/span>确定<\/a>\n";
		strEdit += "	<\/div>\n";
		strEdit += "<\/div>\n";

		strAction += "<div id=\"picture\" class=\"mui-popover mui-popover-action mui-popover-bottom\">\n";
		strAction += "	<ul class=\"mui-table-view\">\n";
		strAction += "		<li class=\"mui-table-view-cell\">\n";
		strAction += "		<a href=\"#\" id=\"getImage\">拍照<\/a>\n";
		strAction += "		<\/li>\n";
		strAction += "		<li class=\"mui-table-view-cell\">\n";
		strAction += "		<a href=\"#\" id=\"galleryImgs\">图库<\/a>\n";
		strAction += "		<\/li>\n";
		strAction += "	<\/ul>\n";
		strAction += "	<ul class=\"mui-table-view\">\n";
		strAction += "		<li class=\"mui-table-view-cell\">\n";
		strAction += "		<a href=\"#picture\" id=\"cancel\"><b>取消<\/b><\/a>\n";
		strAction += "		<\/li>\n";
		strAction += "	<\/ul>\n";
		strAction += "<\/div>\n";

		strCss += "<style type=\"text/css\">\n";
		strCss += "			#" + obj.uploadListId + " {\n";
		strCss += "				display: flex;\n";
		strCss += "				justify-content: flex-start;\n";
		strCss += "				flex-wrap: wrap;\n";
		strCss += "				padding: 10px 0;\n";
		strCss += "				padding-bottom: calc(10px - 2vw);\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#" + obj.uploadListId + " .pic {\n";
		strCss += "				position: relative;\n";
		strCss += "				display: inline-block;\n";
		/*		strCss += "				font-size: 0;\n";
				strCss += "				-webkit-text-size-adjust:none;\n";*/
		strCss += "				width: 32vw;\n";
		strCss += "				height: 32vw;\n";
		strCss += "				margin: 0 2vw 2vw 0;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#" + obj.uploadListId + " img {\n";
		strCss += "				width: 100%;\n";
		strCss += "				height: 100%;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#" + obj.uploadListId + " .btnlist {\n";
		strCss += "				position: absolute;\n";
		strCss += "				left: 0;\n";
		strCss += "				top: 0;\n";
		strCss += "				width: 100%;\n";
		strCss += "				/*height: 100%;*/\n";
		strCss += "				z-index: 99;\n";
		strCss += "				display: flex;\n";
		strCss += "				justify-content: space-around;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#" + obj.uploadListId + " .pic.mui-icon:before {\n";
		strCss += "				position: absolute;\n";
		strCss += "				left: 0;\n";
		strCss += "				top: 0;\n";
		strCss += "				font-size: 60px;\n";
		strCss += "				height: 100%;\n";
		strCss += "				width: 100%;\n";
		strCss += "				line-height: 32vw;\n";
		strCss += "				text-align: center;\n";
		strCss += "				color: chartreuse;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#" + obj.uploadListId + " .pic.uploading:before {\n";
		strCss += "				color: #ECB100;\n";
		strCss += "				font-size: 50px;\n";
		strCss += "				-webkit-animation: spinner-spin 1s step-end infinite;\n";
		strCss += "				animation: spinner-spin 1s step-end infinite;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#" + obj.uploadListId + " .pic.mui-icon-closeempty:before {\n";
		strCss += "				color: #FF5053;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#" + obj.uploadListId + " .pic:nth-child(3n) {\n";
		strCss += "				margin: 0 0 2vw 0;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#showEdit {\n";
		strCss += "				width: 100%;\n";
		strCss += "				height: 100%;\n";
		strCss += "				background-color: #fff;\n";
		strCss += "				position: fixed;\n";
		strCss += "				top: 0;\n";
		strCss += "				left: 150%;\n";
		//		strCss += "				display: none;\n";
		strCss += "				z-index: 9999;\n";
		strCss += "				background: #333;\n";
		strCss += "				opacity: 0;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#report {\n";
		strCss += "				height: 100%;\n";
		strCss += "				width: 100%;\n";
		strCss += "				z-index: 10;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#readyimg {\n";
		strCss += "				display: none;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			#showEdit .flex-container {\n";
		strCss += "				background: #FAFAFA;\n";
		strCss += "				line-height: 60px;\n";
		strCss += "				display: flex;\n";
		strCss += "				justify-content: space-around;\n";
		strCss += "				position: absolute;\n";
		strCss += "				bottom: 0;\n";
		strCss += "				left: 0;\n";
		strCss += "				width: 100%;\n";
		strCss += "				opacity: .8;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			.mui-btn {\n";
		strCss += "				height: 40px;\n";
		strCss += "				padding: 0;\n";
		strCss += "			}\n";
		strCss += "			\n";
		strCss += "			a.mui-icon-plus {\n";
		strCss += "				width: 32vw;\n";
		strCss += "				height: 32vw;\n";
		strCss += "				margin: 0 0 2vw 0;\n";
		strCss += "				line-height: 32vw;\n";
		strCss += "				text-align: center;\n";
		strCss += "				font-size: 70px;\n";
		strCss += "				display: inline-block;\n";
		strCss += "				vertical-align: top;\n";
		strCss += "			}\n";
		strCss += ".mui-spinner-custom:before {\n";
		strCss += "				content: \"\";\n";
		strCss += "				background: no-repeat center;\n";
		strCss += "             background-image: url(\"data:image/svg+xml;charset=utf-8,<svg viewBox='0 0 120 120' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><defs><line id='l' x1='60' x2='60' y1='7' y2='27' stroke='red' stroke-width='11' stroke-linecap='round'/><\/defs><g><use xlink:href='%23l' opacity='.27'/><use xlink:href='%23l' opacity='.27' transform='rotate(30 60,60)'/><use xlink:href='%23l' opacity='.27' transform='rotate(60 60,60)'/><use xlink:href='%23l' opacity='.27' transform='rotate(90 60,60)'/><use xlink:href='%23l' opacity='.27' transform='rotate(120 60,60)'/><use xlink:href='%23l' opacity='.27' transform='rotate(150 60,60)'/><use xlink:href='%23l' opacity='.37' transform='rotate(180 60,60)'/><use xlink:href='%23l' opacity='.46' transform='rotate(210 60,60)'/><use xlink:href='%23l' opacity='.56' transform='rotate(240 60,60)'/><use xlink:href='%23l' opacity='.66' transform='rotate(270 60,60)'/><use xlink:href='%23l' opacity='.75' transform='rotate(300 60,60)'/><use xlink:href='%23l' opacity='.85' transform='rotate(330 60,60)'/><\/g><\/svg>\");\n";
		strCss += "            	background-size: 45px 45px;\n";
		strCss += "            }\n";
		strCss += "		<\/style>\n";

		//		strAdd += "<a id=\"addbtn\" class=\"mui-icon mui-icon-plus\" href=\"#picture\"><\/a>\n";
		var inputVar = "";
		inputVar += "<input type=\"file\" accept=\"image/*\" id=\"capture\" capture=\"camera\" style=\"display:none\" multiple=\"multiple\"/>\n";
		$("#" + obj.startUploadId).addClass("mui-disabled"); //初始让上传按钮不可用
		$("head").append(strCss);
		$("body").append(strEdit);
		$("body").append(strAction);
		$("body").append(inputVar);
	};

	//拍照  
	function getImage() {
		if(window.plus) {
			var cmr = plus.camera.getCamera();
			cmr.captureImage(function(p) {
				plus.io.resolveLocalFileSystemURL(p, function(entry) {
					var localurl = entry.toLocalURL();
					var newItem = addpicItem(localurl);
					if(headId != "") {
						if($("#" + headId).attr("cut")) {
							$("#" + headId + " img").addClass("cuting");
							cutImg().showEdit(localurl);
						} else {
							var $img = $(newItem).find("img");
							$("#" + headId).html($img).removeClass("mui-icon-checkmarkempty uploading mui-spinner-custom mui-icon-closeempty");
							if(!$("#" + headId).attr("noauto")) {
								$("#" + headId).addClass("uploading mui-icon mui-spinner-custom mui-spin");
								getBase64($("#" + headId + " img"));
							}
						}
						headId = "";
					} else {
						$("#" + addId).before(newItem);
					};
				});
			}, function(p) {
				headId = "";
				addId = "";
			});
		} else {
			mui.toast("当前设备不支持拍照")
		}
	};
	//相册选取  
	function galleryImgs() {
		if(window.plus) {
			plus.gallery.pick(function(e) {
				getImagefile(e);
			}, function(e) {
				headId = "";
				addId = "";
				//outSet( "取消选择图片" );  
			}, {
				filter: "image"
			});
		} else {
			$("#capture").trigger("click");
		};

	};

	function getImagefile(url) {
		var newItem = addpicItem(url);
		if(headId != "") {
			if($("#" + headId).attr("cut")) {
				$("#" + headId + " img").addClass("cuting");
				cutImg().showEdit(url);
			} else {
				var $img = $(newItem).find("img");
				$("#" + headId).html($img).removeClass("mui-icon-checkmarkempty uploading mui-spinner-custom mui-icon-closeempty");
				if(!$("#" + headId).attr("noauto")) {
					$("#" + headId).addClass("uploading mui-icon mui-spinner-custom mui-spin");
					getBase64($("#" + headId + " img"));
				}

			}
			headId = "";
		} else {
			$("#" + addId).before(newItem);
		};
	}
	//照片裁剪类  
	function cutImg() {

		//$image.cropper('zoom',-0.5);
		var $readyimg = $('#readyimg');
		var $showEdit = $("#showEdit");
		return {
			showEdit: function(imgsrc) {
				$readyimg.attr({ src: imgsrc });
				$showEdit.animate({ "left": 0 }, 200, function() {
					$showEdit.css({ "opacity": 1 });
				});
				$readyimg.cropper({
					center: false,
					cropBoxMovable: false,
					cropBoxResizable: false,
					viewMode: 1,
					dragMode: "move",
					guides: false,
					background: false,
					aspectRatio: 1 / 1,
					autoCropArea: 1,
					zoom: -0.2,
				});

			},
			addevent: function() {
				$("#confirm").on("tap", this.confirm); //裁剪确定
				$("#rotateimg").on("tap", this.rotateimg); //裁剪右旋转
				$("#rotateimgleft").on("tap", this.rotateimgleft); //裁剪左旋转
				$("#closepop").on("tap", this.closepop); //取消关闭裁剪
				$("#resetpop").on("tap", this.resetpop);

			},
			confirm: function() {
				var $cuting = $(".cuting");
				$showEdit.css({ "left": "150%", "opacity": 0 });
				var dataURL = $readyimg.cropper("getCroppedCanvas", { fillColor: $("body").css("background-color") });
				//var imagurl = dataURL.toString();
				var imgurl = dataURL.toDataURL("image/jpeg", 0.5);
				$cuting.attr("src", imgurl);
				$cuting.parent().removeClass("mui-icon-checkmarkempty uploading mui-spinner-custom mui-icon-closeempty");
				if(!$cuting.parent().attr("noauto") && $cuting.parent().attr("href")) {
					$cuting.parent().addClass("uploading mui-icon mui-spinner-custom mui-spin");
					getBase64($cuting);
				};
				$cuting.removeClass("cuting");
				$readyimg.cropper('destroy');
			},
			rotateimg: function() {
				$readyimg.cropper('rotate', 90);
			},
			rotateimgleft: function() {
				$readyimg.cropper('rotate', -90);
			},
			closepop: function() {
				var $cuting = $(".cuting");
				/*if($cuting.parent().attr("autoupload")) {
					$cuting.parent().addClass("uploading mui-icon mui-spinner-custom mui-spin");
					getBase64($cuting);
				};*/
				$cuting.removeClass("cuting");
				$showEdit.css({ "left": "150%", "opacity": 0 });
				$readyimg.cropper('destroy');
			},
			resetpop: function() {
				$readyimg.cropper('reset');
			}
		}
	};

	function getUptoken(bol) { //获得服务器验证uptoken
		if(bol || !sessionStorage.uptoken) {
			$.ajax({
				//url: 'http://192.168.146.134:8080/qiniuTest/getToken?bucket=test1',
				//url: 'http://10.8.45.1:8080/qiniuTest/getToken?bucket=test1',
				//url: 'http://10.8.45.39:8080/qiniuTest/getToken?bucket=test1',
				url: obj.uptokenUrl,
				type: "get",
				timeout: 10000,
				dataType: "jsonp",
				jsonp: "callback",
				jsonpCallback: "qiniucallback",
				contentType: "application/x-www-form-urlencoded; charset=utf-8",
				success: function(data) {
					sessionStorage.uptoken = data.uptoken;
				}
			});
		};
	};

	function addpicItem(src) { //传进来的url去生成一个div包裹该url的图片和编辑+删除按钮
		var strVar = "";
		strVar += "<a class=\"pic\">\n";
		strVar += "<p class=\"btnlist mui-hidden\">\n";
		strVar += "		<button class=\"mui-icon mui-icon-trash\"><\/button>\n";
		strVar += "		<button class=\"mui-icon mui-icon-compose\"><\/button>\n";
		strVar += "<\/p>";
		strVar += "<img src='" + src + "'/>";
		strVar += "<\/a>";
		if(headId == "") {
			$("#" + obj.startUploadId).removeClass("mui-disabled");
			var $uploadimgArr = $("#" + addId).parent().find(".pic");
			if($uploadimgArr.length >= obj.uploadMax - 1) {
				$("#" + addId).hide();
			}
		}
		return strVar;
	};

	function getBase64($img) {
		var $imgSrc = $img.attr("src");
		if($imgSrc.indexOf("base64,") == -1 && $imgSrc.indexOf("clouddn.com") == -1) {
			var format = ($imgSrc.indexOf(".png") == -1 ? "image/jpeg" : "image/png");
			var newImg = document.createElement('img'); //得到img的原始尺寸去创建
			newImg.src = $imgSrc;
			newImg.onload = function() {
				var data = getBase64Image(newImg, format);
				putb64(data, -1, $img);
			};
			//document.body.appendChild(img);
		} else if($imgSrc.indexOf("clouddn.com") != -1) {
			return;
		} else {
			putb64($imgSrc, -1, $img);
		}
	};

	function getBase64Image(img, imgformat) { //获得img的base64
		var canvas = document.createElement("canvas");
		var rate = imgformat == "image/png" ? 0.2 : 0.5;
		canvas.width = img.width;
		canvas.height = img.height;

		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, img.width, img.height);

		var dataURL = canvas.toDataURL(imgformat, rate);
		return dataURL
	};

	function putb64(base64, size, $img) { //base64：上传到7牛base64的图片编码，size:未转码base64时的大小可以传-1，$img对象。
		xhrNumber++;
		var replacestr = base64.substr(0, base64.indexOf(";base64,") + 8);
		//		alert(base64.length)
		var pic = base64.replace(replacestr, "");
		//		var pic = base64.replace("data:image/jpeg;base64,", "");
		var xhr = new XMLHttpRequest();
		var url = "http://upload.qiniu.com/putb64/" + size;
		var picUrl = "";
		xhr.onreadystatechange = function() {
			if(xhr.readyState == 4) {
				//这里可以判断图片上传成功,而且可以通过responseText获取图片链接
				//var data = JSON.parse(xhr.responseText);
				//console.log(xhr.responseText);
				//图片链接就是yourcdnpath.xx/data.key
				var keyText = xhr.responseText;
				/*返回的key是字符串，需要装换成json*/
				keyText = strToJson(keyText);
				/* http://oe8wmyqo6.bkt.clouddn.com/是我的七牛云空间网址，keyText.key 是返回的图片文件名*/
				var newImgUrl = document.createElement("input");
				$(newImgUrl).addClass("mui-hidden").attr("type", "text");
				if(keyText.key) { //如果返回的有key，则上传成功
					picUrl = obj.picUrl + "/" + keyText.key; //拼出上传后图片的url
					newImgUrl.name = "picurl" + n;
					$img.parent().removeClass("uploading mui-spinner-custom").addClass(function() {
						xhrNumber--;
						if(xhrNumber == 0) {
							mui.toast("上传完成");
							if(obj.hideLoaded) {
								setTimeout(function() {
									$("#" + obj.uploadListId + " .pic.uploadsuccess").remove();
								}, 1000);
							}
						};
						return "mui-icon-checkmarkempty uploadsuccess";
					});
				} else {
					$img.parent().removeClass("uploading mui-spinner-custom").addClass("mui-icon-closeempty");
					picUrl = "上传错误,请重新上传！";
					newImgUrl.name = "uploadfail";
				};
				newImgUrl.value = picUrl;
				$("#" + obj.startUploadId).before(newImgUrl);
			}
		}
		xhr.open("POST", url, true);
		xhr.setRequestHeader("Content-Type", "application/octet-stream");
		xhr.setRequestHeader("Authorization", "UpToken " + sessionStorage.uptoken);
		xhr.send(pic);
	};

	function strToJson(str) { //返回的hash和key字符串转成json
		var json = eval('(' + str + ')');
		return json;
	};
};